// encoding: utf-8
// Copyright 2012, Google Inc. All Rights Reserved.

/////////////////////////////////////////////////////////////////////
// GLOBALS

var timerID = null;
var state = { };

/////////////////////////////////////////////////////////////////////
// GET REQUESTS

function getHTTPObject() {
    if (typeof XMLHttpRequest != 'undefined') {
        return new XMLHttpRequest();
    }
    try {
        return new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            return new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
    }
    return null;
}

function get_request(method,uri,data,callback) {
 	req = getHTTPObject();
	req.open(method,uri,true);
	if(callback) {
		req.onreadystatechange = function(r) {
			if(req.readyState == 4) {
				callback(req.status,req.responseText);
			}
		}
	}
	req.send(data);
	return req;
}

/////////////////////////////////////////////////////////////////////
// EVENTS

function event_interval_changed(secs) {
	window.console && console.log && console.log("Setting interval to " + secs + " secs")
	if(secs >= 0) {
		start_timer(secs);
	}
}

function event_state_changed(key) {
	window.console && console.log && console.log("State has changed for gadget: " + key)
	/* find the appropriate DIV element */
	divNode = document.getElementById("block-" + key)
	if(divNode) {
		/* get the iframe tag within the DIV element, and reload */
		for(var i = 0; i < divNode.childNodes.length; i++) {
			var childNode = divNode.childNodes[i]
			if(childNode.nodeType==1) {
				if(navigator.appName == "Microsoft Internet Explorer") {
				    childNode.contentWindow.location.reload(true);
				} else {
				    childNode.src = childNode.src;
				}
			}
		}
	}
}

/////////////////////////////////////////////////////////////////////
// CALLBACKS

function callback_fetch_state(status,response) {
	if(status != 200) {
		window.console && console.log && console.log("callback_fetch_state: ignoring status " + status);
		return;
	}
	var json = eval('('+ req.responseText +')');
	if(json) {
		for(key in json) {
			if(typeof key != "string") {
				continue;
			}
			new_value = json[key]
			old_value = state[key]
			if(key=="interval" && typeof(new_value)=="number" && (old_value != new_value)) {
				event_interval_changed(new_value);
				state[key] = new_value;
			} else if(typeof(new_value)=="number" && (old_value != new_value)) {
				event_state_changed(key);
				state[key] = new_value;
			}
		}
	}
}

/////////////////////////////////////////////////////////////////////
// GET REQUESTS

function fetch_state() { 
	get_request("GET","/state.js",null,callback_fetch_state); 
}

function start_timer(secs) {
	if(timerID) {
		clearInterval(timerID);
	}
	timerID = null;
	if(secs > 0) {
		timerID = setInterval(fetch_state,secs * 1000);
	}
}

if(document.body) {
	document.body.onload = function() {
		// start timer with 10 second delay
		start_timer(10);
	}
}
